package com.century.sjt.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.Constant;
import com.century.sjt.EMChat.activity.ChatActivity;
import com.century.sjt.EMChat.adapter.EaseContactAdapter;
import com.century.sjt.EMChat.domain.EaseUser;
import com.century.sjt.EMChat.ui.EaseBaseActivity;
import com.century.sjt.EMChat.widget.EaseSidebar;
import com.century.sjt.R;
import com.century.sjt.SjtHelper;
import com.century.sjt.activity.Pay.CommodityActivity;
import com.century.sjt.util.FileUtil;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;


public class ShareFriendActivity extends BaseActivity {

    private ListView listView;
    private EaseSidebar sidebar;
    protected EaseContactAdapter contactAdapter;
    private List<EaseUser> contactList;
    private SjtTitleBar titleBar;

    private EditText queryEditText;
    protected ImageButton clearSearch;
    private String url;
    private String ShopId,GoodId;
    private String shareUrl,goodName,mainImageUrl;
    private String shopUserId,price,type;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sjt_choose_afriend_activity);

        Intent intent=getIntent();
        type = intent.getStringExtra("type");
        if ("goods".equals(type)){
            url=intent.getStringExtra("url");//商品详情连接
            ShopId = intent.getStringExtra("shopId");//商家ID
            GoodId = intent.getStringExtra("goodId");//商品ID
            shareUrl = intent.getStringExtra("shareUrl");//分享链接
            goodName = intent.getStringExtra("goodName");//商品名称
            mainImageUrl = intent.getStringExtra("mainImageUrl");//商品主图
            shopUserId = intent.getStringExtra("shopUserId");//商家用户ID
            price = intent.getStringExtra("price");//商品单价
        }
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        titleBar.setTitle(getResources().getString(R.string.select_contacts));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        listView = (ListView) findViewById(R.id.list);
        sidebar = (EaseSidebar) findViewById(R.id.sidebar);
        sidebar.setListView(listView);
        queryEditText = (EditText) findViewById(R.id.query);
        clearSearch = (ImageButton) findViewById(R.id.search_clear);
        contactList = new ArrayList<EaseUser>();
        // 获取设置contactlist
        getContactList();
        // 设置adapter
        contactAdapter = new EaseContactAdapter(this, R.layout.ease_row_contact, contactList);
        listView.setAdapter(contactAdapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                onListItemClick(position);
            }
        });
        //软键盘设置
        queryEditText.setOnEditorActionListener(new TextView.OnEditorActionListener(){
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                 /*判断是否是“GO”键*/
                if(actionId == EditorInfo.IME_ACTION_SEARCH){
                    /*隐藏软键盘*/
                    InputMethodManager imm = (InputMethodManager) v
                            .getContext().getSystemService(
                                    Context.INPUT_METHOD_SERVICE);
                    if (imm.isActive()) {
                        imm.hideSoftInputFromWindow(
                                v.getApplicationWindowToken(), 0);
                    }

                    if (queryEditText.getText().length() == 0 || "".equals(queryEditText.getText().toString())) {
                        getContactList();
                    } else {
                        seabarUser(queryEditText.getText().toString().trim());
                    }
                    contactAdapter.notifyDataSetChanged();
                    return true;
                }
                return false;
            }
        });
        queryEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (s.length() > 0) {
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    clearSearch.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (queryEditText.getText().length() == 0 || "".equals(queryEditText.getText().toString())) {
                    getContactList();
                } else {
                    seabarUser(queryEditText.getText().toString().trim());
                }
                contactAdapter.notifyDataSetChanged();
            }

        });
        clearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                queryEditText.getText().clear();
                hideSoftKeyboard();
            }
        });

    }

    protected void onListItemClick(int position) {
//
        sendTextMessage(goodName,contactList.get(position).getUsername());
        startActivity(new Intent(ShareFriendActivity.this, ChatActivity.class).putExtra("userId",contactList.get(position).getUsername()));

    }


    private void getContactList() {
        contactList.clear();
        Map<String, EaseUser> users = SjtHelper.getInstance().getContactList();
        Iterator<Map.Entry<String, EaseUser>> iterator = users.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, EaseUser> entry = iterator.next();
            SharedPreferences mainSharedPreferences = getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
            String userId = mainSharedPreferences.getString("userId", "");
            if (!entry.getKey().equals(Constant.NEW_FRIENDS_USERNAME) && !entry.getKey().equals(Constant.GROUP_USERNAME) && !entry.getKey().equals(Constant.CHAT_ROOM) && !entry.getKey().equals(Constant.CHAT_ROBOT))
//                if (!entry.getValue().getUsername().equals("00000000")) {
//                    if ("0".equals(entry.getValue().getIsShop())) {
//                        contactList.add(entry.getValue());
//                    }
//                }

            if (!entry.getValue().getUsername().equals("00000000")&&!entry.getValue().getUsername().equals(userId)){
                if ("0".equals(entry.getValue().getIsShop())){
                    contactList.add(entry.getValue());
                }
//                            contactList.add(user);
            }
        }
        // 排序
        Collections.sort(contactList, new Comparator<EaseUser>() {

            @Override
            public int compare(EaseUser lhs, EaseUser rhs) {
                if (lhs.getInitialLetter().equals(rhs.getInitialLetter())) {
                    return lhs.getNick().compareTo(rhs.getNick());
                } else {
                    if ("#".equals(lhs.getInitialLetter())) {
                        return 1;
                    } else if ("#".equals(rhs.getInitialLetter())) {
                        return -1;
                    }
                    return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
                }

            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initData() {

    }

    /**
     * list 模糊搜索好友
     */
    public void seabarUser(final String srcName){
        for(int i=0;i<contactList.size();i++ ){
            if(((EaseUser)(contactList.get(i))).getNick().indexOf(srcName)<=-1){
                contactList.remove(i);
            }
        }
        // 排序
        Collections.sort(contactList, new Comparator<EaseUser>() {

            @Override
            public int compare(EaseUser lhs, EaseUser rhs) {
                if (lhs.getInitialLetter().equals(rhs.getInitialLetter())) {
                    return lhs.getNick().compareTo(rhs.getNick());
                } else {
                    if ("#".equals(lhs.getInitialLetter())) {
                        return 1;
                    } else if ("#".equals(rhs.getInitialLetter())) {
                        return -1;
                    }
                    return lhs.getInitialLetter().compareTo(rhs.getInitialLetter());
                }

            }
        });

    }

    //发送消息方法
    //==========================================================================
    protected void sendTextMessage(String content,String toUserID) {
        EMMessage message = EMMessage.createTxtSendMessage(content, toUserID);
        message.setAttribute("ext_type","2");
        message.setAttribute("price",price);
        message.setAttribute("shopId",ShopId);
        message.setAttribute("goodId",GoodId);
        message.setAttribute("mainImageUrl",mainImageUrl);
        message.setAttribute("detailsUrl",url);
        message.setAttribute("goodName",goodName);
        message.setAttribute("shareUrl",shareUrl);
        EMChatManager.getInstance().sendMessage(message, null);
    }
}



